<?php

namespace app\admin\controller\agent;

use app\admin\model\agent\MoneyLog;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\Log;
use Throwable;

/**
 * 代理商提现管理
 */
class Withdrawal extends Backend
{
    /**
     * Withdrawal模型对象
     * @var object
     * @phpstan-var \app\admin\model\agent\Withdrawal
     */
    protected object $model;

    protected string|array $defaultSortField = 'withdrawal_id,desc';

    protected array|string $preExcludeFields = ['create_time'];

    protected string|array $quickSearchField = ['withdrawal_id'];

    protected array $withJoinTable = ['agent'];

    public function initialize (): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\agent\Withdrawal;
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */


    /**
     * 查看
     * @throws Throwable
     */
    public function index (): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }
        $newWhere = [];
        if ($this->auth->getInfo()['is_agent'] == 1) {
            $newWhere[] = ['agent_id', '=', $this->auth->id];
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($newWhere)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 添加
     */
    public function add (): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                #判断提现金额是否大于余额
                $agentInfo = \app\admin\model\Admin::where('id', $this->auth->id)->find();
                if ($data['price'] <= 0) {
                    $this->error('金额不能小于0');
                }
                if ($agentInfo->money < $data['price']) {
                    $this->error('提现金额大于余额');
                }
                $agentInfo->money = bcsub($agentInfo->money, $data['price'], 2);
                $agentInfo->save();
                $data['agent_id'] = $this->auth->id;
                $result = $this->model->save($data);
                #记录到代理商余额变动表
                $agentMoneyLog = new MoneyLog();
                $agentMoneyLogInfo = $agentMoneyLog->where('agent_id', $this->auth->id)->order('create_time', 'desc')->find();
                $agentMoneyLog->agent_id = $this->auth->id;
                $agentMoneyLog->money = $data['price'];
                $agentMoneyLog->before = $agentMoneyLogInfo->after;
                $agentMoneyLog->after = bcsub($agentMoneyLogInfo->after, $data['price'], 2);
                $agentMoneyLog->type = 4;
                $agentMoneyLog->memo = '提现';
                $agentMoneyLog->create_time = date('Y-m-d H:i:s', time());
                $agentMoneyLog->withdrawal_id = $this->model->withdrawal_id;
                $agentMoneyLog->save();
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    /**
     * 设置已付款
     * @return void
     */
    public function payment (): void
    {
        $id = $this->request->get('id');
        $ret = $this->model->where('withdrawal_id', $id)->update(['status' => 1]);
        if (!$ret) {
            $this->error('设置失败');
        }
        $this->success('', $ret);
    }


    /**
     * 驳回提现
     * @return void
     */
    public function reject (): void
    {
        #开启事务
        Db::startTrans();
        try {
            $id = $this->request->get('id');
            $msg = $this->request->get('msg');
            $ret = $this->model->where('withdrawal_id', $id)->find();
            $ret->status = 2;
            $ret->msg = $msg;
            $ret->save();

            #将金额退回到技师余额
            $agent_id = $ret->agent_id;
            $agentInfo = \app\admin\model\Admin::where('id', $agent_id)->find();
            $agentInfo->money = bcadd($agentInfo->money, $ret->price, 2);
            $agentInfo->save();

            #记录到代理商余额变动表
            $agentMoneyLog = new MoneyLog();
            $agentMoneyLogInfo = $agentMoneyLog->where('agent_id', $agent_id)->order('create_time', 'desc')->find();
            $agentMoneyLog->agent_id = $agent_id;
            $agentMoneyLog->money = $ret->price;
            $agentMoneyLog->before = $agentMoneyLogInfo->after;
            $agentMoneyLog->after = bcadd($agentMoneyLogInfo->after, $ret->price, 2);
            $agentMoneyLog->type = 5;
            $agentMoneyLog->memo = '提现驳回 ' . $msg;
            $agentMoneyLog->create_time = date('Y-m-d H:i:s', time());
            $agentMoneyLog->save();
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::error('提现驳回失败- ' . $e->getMessage());
            $this->error('驳回失败');
        }
        $this->success('驳回成功');
    }

}